//
//  ZMJMusicViewController.m
//  Z-QQMusic
//
//  Created by zmj on 15/11/5.
//  Copyright © 2015年 zmj. All rights reserved.
//

#import "ZMJMusicViewController.h"
#import "ZMJAudioTool.h"
#import "ZMJMUsicsTool.h"
#import "ZMJMusic.h"
#import "NSString+ZMJExtension.h"
#import "CALayer+PauseAimate.h"
#import "ZMJLrcView.h"
#import "ZMJLrcLabel.h"
@interface ZMJMusicViewController ()<AVAudioPlayerDelegate,UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *musicNameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *singerIconImageView;
@property (weak, nonatomic) IBOutlet UILabel *singerNameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *backGroundImageView;
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
@property (weak, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalTimeLabel;
@property (weak, nonatomic) IBOutlet ZMJLrcLabel *lrcLabel;

@property (weak, nonatomic) IBOutlet UIButton *playOrPauseButton;

@property (weak, nonatomic) IBOutlet ZMJLrcView *lrcScrollView;

@property(nonatomic, weak) AVAudioPlayer *currentPlayer;/**< 音频播放器 */
@property(nonatomic, weak) NSTimer *updateTimeLableTimer;/**< 更新显示歌曲时间label的定时器 */
@property(nonatomic, strong) CADisplayLink *lrcTimer;/**< 更新歌词显示的timer */


@end

@implementation ZMJMusicViewController
- (IBAction)backiButtonClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 歌曲开始播放相关设置
    [self musicStartSetting];
    // 设置progressSlider
    [self setupProgressSlider];
    
    // 当前界面的歌词label显示的方式和效果交给歌词scrollView
    self.lrcScrollView.lrcLabel = self.lrcLabel;
    
    self.view.backgroundColor = [UIColor whiteColor];
}

/**
 *  将布局子控件,自身的frame已经是调整好的正确的
 */
- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.singerIconImageView.layer.cornerRadius = self.singerIconImageView.bounds.size.width * 0.5;
    self.singerIconImageView.layer.masksToBounds = YES;
    
    // 设置歌词scrollView(这里的frame是准确的,viewDidLoad中scrollView的宽高是storyBoard中的宽高)
    [self setupLrcScrollView];
}


- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self playOrPauseButtonTouchDownClick:self.playOrPauseButton];
            break;
            
        case UIEventSubtypeRemoteControlPreviousTrack:
            [self previousMusicButtonClick];
            break;
            
        case UIEventSubtypeRemoteControlNextTrack:
            [self nextMusicButtonClick];
            
        default:
            break;
    }
}


#pragma mark - 初始化

- (void)setupLrcScrollView {
    self.lrcScrollView.delegate = self;
    
}

- (void)musicStartSetting {
    // 开始播放歌曲
    [self startPlayingMusic];
    // 添加动画
    [self addAnimationToSingerIconImageView];
    // 添加定时器
    [self addProgressTimer];
    [self addLrcTimer];
}

/**
 *  开始播放歌曲
 */
- (void)startPlayingMusic {
    // 获取当前播放的歌曲信息
    ZMJMusic *playingMusic = [ZMJMusicsTool playingMusic];
    // 设置基本数据
    self.musicNameLabel.text = playingMusic.name;
    self.singerIconImageView.image = [UIImage imageNamed:playingMusic.icon];
    self.singerNameLabel.text = playingMusic.singer;
    self.backGroundImageView.image = [UIImage imageNamed:playingMusic.icon];
    
    // 开始播放
    self.currentPlayer = [ZMJAudioTool playingMusicWithName:playingMusic.filename];
    self.currentPlayer.delegate = self;
    self.currentTimeLabel.text = [NSString stringwithNSTimeInterval:self.currentPlayer.currentTime];
    self.totalTimeLabel.text = [NSString stringwithNSTimeInterval:self.currentPlayer.duration];
    
    // 设置歌曲名和时长
    self.lrcScrollView.lrcName = playingMusic.lrcname;
    self.lrcScrollView.duration = self.currentPlayer.duration;

}

- (void)addAnimationToSingerIconImageView {

    // 创建动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
//    [animation setKeyPath:@"transform.rotation.z"];
    animation.fromValue = @(0);
    animation.toValue = @(M_PI * 2);
    animation.repeatCount = MAXFLOAT;
    animation.duration = 40;
    // 添加动画
    [self.singerIconImageView.layer addAnimation:animation forKey:nil];
    
    // 开始动画
}

/**
 *  添加歌曲进度定时器
 */
- (void)addProgressTimer {
    // 开始定时器
    [self.updateTimeLableTimer invalidate]; // 先移除
    self.updateTimeLableTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimeLabel) userInfo:nil repeats:YES];
    [self.updateTimeLableTimer fire];
}
/**
 *  添加歌词显示定时器
 */
- (void)addLrcTimer {
    [self.lrcTimer invalidate];
    self.lrcTimer = nil;
    self.lrcTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLrc)];
    [self.lrcTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

/**
 *  设置progressSlider
 */
- (void)setupProgressSlider {
    [self.progressSlider setThumbImage:[UIImage imageNamed:@"player_slider_playback_thumb"] forState:UIControlStateNormal];
    [self.progressSlider addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(progressSliderTap:)]];
}

#pragma mark - 更新歌词显示
- (void)updateLrc {
    [self.lrcScrollView setCurrnetTime:self.currentPlayer.currentTime];
}

#pragma mark - 更新控制歌曲播放时间
- (void)updateTimeLabel {
    
    self.currentTimeLabel.text = [NSString stringwithNSTimeInterval:self.currentPlayer.currentTime];
    self.progressSlider.value = self.currentPlayer.currentTime / self.currentPlayer.duration;
}

- (void)progressSliderTap:(UITapGestureRecognizer *)tapGestureRecognizer {
    CGPoint point = [tapGestureRecognizer locationInView:self.progressSlider];
    self.progressSlider.value = point.x / self.progressSlider.bounds.size.width;
    [self.currentPlayer setCurrentTime:self.progressSlider.value * self.currentPlayer.duration];
    [self addProgressTimer];
    [self addLrcTimer];
}

/**
 *  拖动slider时,停止播放,松手开始播放
 */
- (IBAction)progressSliderValueChange {
    if ([self.currentPlayer isPlaying]) {
        [self.currentPlayer pause];
        self.playOrPauseButton.selected = NO;
        
    }
    [self.currentPlayer setCurrentTime:self.progressSlider.value * self.currentPlayer.duration];
    
    
}
- (IBAction)progressSliderTouchUpInside {
    [self.currentPlayer play];
    self.playOrPauseButton.selected = YES;
}



#pragma mark - 歌曲播放控制

- (IBAction)playOrPauseButtonTouchDownClick:(UIButton *)sender {
    if (sender.selected) {
        [self.currentPlayer pause];
        [self.updateTimeLableTimer invalidate];
        [self.lrcTimer invalidate];
        [self.singerIconImageView.layer pauseAnimate];
    }else {
        [self.currentPlayer play];
        [self updateTimeLableTimer];
        [self addProgressTimer];
        [self addLrcTimer];
        [self.singerIconImageView.layer resumeAnimate];

    }
    sender.selected = !sender.selected;
}


- (IBAction)previousMusicButtonClick {
    [self stopMusic];
    [ZMJMusicsTool previousMusic];
    [self musicStartSetting];
    
}

- (IBAction)nextMusicButtonClick {
    [self stopMusic];
    [ZMJMusicsTool nextMusic];
    [self musicStartSetting];

}

- (void)stopMusic {
    [ZMJAudioTool stopMusicWithMusicName:[ZMJMusicsTool playingMusic].filename];
}


#pragma mark - AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {

    if (flag) { // 成功播放完毕
        // 播放下一首
        [self nextMusicButtonClick];
    }
}

#pragma - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView { // 滚动一个屏幕距离 - 1
    CGFloat ratio = 1 / self.view.bounds.size.width;
    self.singerIconImageView.alpha = 1 - ratio * scrollView.contentOffset.x;
    self.lrcLabel.alpha = self.singerIconImageView.alpha;
}

#pragma mark - 状态栏样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
